<script lang="ts">
export default {
  name: "TriggerConfigEditDialog"
}
</script>

<!--
 * @Description: 编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" min-width="200px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="80px">

      <!-- 编辑框：配置名称 -->
      <el-form-item label="配置名称" prop="taskName">
        <el-input v-model="dataState.formData.taskName" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <!-- 下拉框：配置类型 -->
      <el-form-item label="设备范围" prop="sourceType">
        <el-select v-model="dataState.formData.sourceType" placeholder="请选择">
          <el-option
            v-for="item in dataState.sourceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 下拉框：设备类型 -->
      <el-form-item label="设备厂商" prop="manufacturer">
        <el-select v-model="dataState.formData.manufacturer" placeholder="请选择"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="dataState.formData.deviceType" placeholder="请选择" @change="handleSelectDeviceType">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <!-- 下拉框：设备名称 -->
      <el-form-item label="设备名称" prop="deviceName">
        <el-select v-model="dataState.formData.deviceName" placeholder="请选择">
          <el-option
            v-for="item in dataState.deviceNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="队列深度" prop="cacheSize">
        <el-input v-model="dataState.formData.cacheSize" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

      <el-form-item label="对象范围" prop="objectType">
        <el-select v-model="dataState.formData.objectType" placeholder="请选择">
          <el-option
            v-for="item in dataState.objectTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="对象列表" prop="objectName">
        <el-input v-model="dataState.formData.objectName" :autosize="{ minRows: 1, maxRows: 6 }" type="textarea"/>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="dataState.formData.description" :autosize="{ minRows: 1, maxRows: 6 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {DeviceValueExTask, DeviceValueExTaskRequestVO} from "@/api/device/valuex/task/types";
import {listOptionList, listOption2List} from "@/api/option";
import {listTaskOptionList} from "@/api/device/valuex/task/taskOption";
import {DeviceQueryParam} from "@/api/device/device/types";
import {listOptions} from "@/api/device/device";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加设备',

  // 表单数据
  formData: {
    id: undefined,
    taskName: '',
    taskParam: {},
    // taskParam展开的参数
    cacheSize: 1,
    sourceType: 'deviceType',
    objectType: 'object',
    objectName: '[]',
    deviceName: '',
    deviceType: '',
    manufacturer: '',
    methodScript: '',
    description: '',
  },

  // 厂商类型选项
  manufacturerOptions: [] as OptionType[],
  deviceTypeOptions: [] as OptionType[],
  deviceNameOptions: [] as OptionType[],
  sourceTypeOptions: [] as OptionType[],
  objectTypeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    taskName: [{required: true, message: '参数不能为空', trigger: 'blur'}],
  },
});

/**
 * 取消
 */
function handleCancel() {
  //执行调用<triggerConfig-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (dataState.formData.taskName === ''){
    ElMessage.info('名称不能为空');
    return;
  }
  if (!dataState.formData.objectName.startsWith("[") || !dataState.formData.objectName.endsWith("]")){
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return;
  }
  let objectNameList = JSON.parse(dataState.formData.objectName);

  if (dataState.formData.sourceType === 'deviceType' && (dataState.formData.manufacturer === '' || dataState.formData.deviceType === '')){
    ElMessage.info('设备类型不能为空');
    return;
  }
  if (dataState.formData.sourceType === 'deviceName' && (dataState.formData.manufacturer === '' || dataState.formData.deviceType === '' || dataState.formData.deviceName === '')){
    ElMessage.info('设备类型不能为空');
    return;
  }
  if (dataState.formData.objectType === 'object' && (objectNameList.length === 0)){
    ElMessage.info('对象类型不能为空');
    return;
  }


  let task = {
    id: undefined,
    taskName: '',
    taskParam: {} as any,
  }

  task.id = dataState.formData.id;
  task.taskName = dataState.formData.taskName;

  task.taskParam.cacheSize = Number(dataState.formData.cacheSize);
  task.taskParam.methodScript = dataState.formData.methodScript;
  task.taskParam.description = dataState.formData.description;

  task.taskParam.dataSource = {} as any;
  task.taskParam.dataSource.manufacturer = dataState.formData.manufacturer;
  task.taskParam.dataSource.deviceType = dataState.formData.deviceType;
  task.taskParam.dataSource.deviceName = dataState.formData.deviceName;
  task.taskParam.dataSource.sourceType = dataState.formData.sourceType;

  task.taskParam.dataSource.dataObject = {} as any;
  task.taskParam.dataSource.dataObject.objectType = dataState.formData.objectType;
  task.taskParam.dataSource.dataObject.objectName = JSON.parse(dataState.formData.objectName);

  if (dataState.type === 'create') {
    emit('create', task);
  }
  if (dataState.type === 'update') {
    emit('update', task);
  }
}

function initEditData(type: string, entity: DeviceValueExTask) {
  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    dataState.formData.id = undefined;
    dataState.formData.taskName = '';
    dataState.formData.taskParam = {};

    nextTick(() => {
      dataFormRef.value.resetFields();
    })

    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    dataState.formData.id = entity.id as any;
    dataState.formData.taskName = entity.taskName;
    dataState.formData.taskParam = entity.taskParam;

    dataState.formData.cacheSize = entity.taskParam.cacheSize;
    dataState.formData.methodScript = entity.taskParam.methodScript;
    dataState.formData.description = entity.taskParam.description;
    dataState.formData.manufacturer = entity.taskParam.dataSource.manufacturer;
    dataState.formData.deviceType = entity.taskParam.dataSource.deviceType;
    dataState.formData.deviceName = entity.taskParam.dataSource.deviceName;
    dataState.formData.sourceType = entity.taskParam.dataSource.sourceType;
    dataState.formData.objectType = entity.taskParam.dataSource.dataObject.objectType;
    dataState.formData.objectName = JSON.stringify(entity.taskParam.dataSource.dataObject.objectName, null, 5);

    return;
  }
}

async function handleSelectManufacturer(value: any) {
  await listOption2List("OperateEntity", "manufacturer", value, 'deviceType').then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (dataState.deviceTypeOptions.length > 0){
      dataState.formData.deviceType = dataState.deviceTypeOptions[0].value;
    }
  });
}

/**
 * 响应通道类型的选择：联动通道类型和通道名称
 * @taskParam value
 */
async function handleSelectDeviceType(value: any) {
  // 查询设备类型下的设备
  let dataForm = {} as DeviceQueryParam;
  dataForm.manufacturer = dataState.formData.manufacturer;
  dataForm.deviceType = dataState.formData.deviceType;
  listOptions("deviceName",dataForm).then(({data}) => {
    dataState.deviceNameOptions = data;
    if (dataState.deviceNameOptions.length>0){
      dataState.formData.deviceName = dataState.deviceNameOptions[0].value;
    }
  });
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 查询厂商选项，并保存在存量区
  listOptionList("OperateEntity", "manufacturer").then(({data}) => {
    for (let time of data){
      dataState.manufacturerOptions.push(time);
    }
  });

  listOptionList("OperateEntity", "deviceType").then(({data}) => {
    for (let time of data){
      dataState.deviceTypeOptions.push(time);
    }
  });

  dataState.sourceTypeOptions = listTaskOptionList("sourceType");
  dataState.objectTypeOptions = listTaskOptionList("objectType");
  dataState.deviceNameOptions.push({value: '', label: ''});
});

</script>
